import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/util/ImCacheFactory.dart';
import 'package:im_app/im/util/ImSingleton.dart';

import '../../pojo/ImPojo.dart';
import '../../socket/dto/business/Login.dart';

final class SessionCubit extends Cubit<SessionState> {
  SessionCubit() : super(SessionState(user: new ImUser(''),
      loginResp: LoginResp(userId: '', tenantCode: '', serverDateTime: DateTime.now(), authCode: 0, token: '', authToken: '', coder: 0,
        successDataTime: DateTime.now(), localSeq: '1',
  )));

  void loginSuccess(ImUser user, LoginResp loginResp) {
    emit(SessionState(user: user, loginResp: loginResp));
  }

  void loadData() async {
    var userId = ImSingleton.getInstance().session.userId;
    if (userId != null) {
      var user = await ImCacheFactory.getInstance().getImUser(userId!);
      emit(SessionState(user: user!, isLogin: true,
          loginResp: LoginResp(userId: '', tenantCode: '', serverDateTime: DateTime.now(), authCode: 0, token: '', authToken: '', coder: 0,
            successDataTime: DateTime.now(), localSeq: '1',
          ))
      );
    } else {
      emit(SessionState(user: ImUser(''),
          loginResp: LoginResp(userId: '', tenantCode: '', serverDateTime: DateTime.now(), authCode: 0, token: '', authToken: '', coder: 0,
            successDataTime: DateTime.now(), localSeq: '1',
          ))
      );
    }
  }
}

final class SessionState extends Equatable {

  final ImUser user;
  final LoginResp loginResp;
  final bool isLogin;

  const SessionState({
    required this.user,
    required this.loginResp,
    this.isLogin = false,
  });

  @override
  List<Object?> get props => [isLogin, user, loginResp];

}